<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .preview {
            display: inline-block;
            width: 100px;
            height: 150px;
            border: 1px solid #ccc;
            vertical-align: middle;
        }
        
        .preview img {
            width: 100%;
            height: 100%;
        }
        
        .file {
            width: 200px;
            outline: none;
            vertical-align: middle;
        }
        
        .box {
            width: 900px;
            height: 35px;
            border-radius: 17.5px;
        }
        
        .progress {
            display: none;
            height: 100%;
            background: blue;
            border-radius: 17.5px;
            line-height: 35px;
            text-align: center;
        }
    </style>
</head>

<body>
    <form id="form">
        <input type="file" class="file">
        <div class="preview"></div>
    </form>
    <div class="box">
        <div class="progress"></div>
    </div>

    <script>
        let file = document.querySelector('.file');
        let preview = document.querySelector('.preview');
        file.onchange = function() {
            let xhr = new XMLHttpRequest();
            xhr.open('post', 'http://localhost:3000/upload');
            let formData = new FormData();
            //为formData对象添加attrName属性，属性值为 this.file[0] ;
            formData.append('attrName', this.files[0]);
            //把fromData对象作为参数传给服务器
            xhr.send(formData);
            xhr.onload = function() {
                // console.log(xhr.responseText);
                if (xhr.status == 200) {
                    preview.innerHTML = '';
                    let img = document.createElement('img');
                    img.src = xhr.responseText;
                    preview.appendChild(img)
                }
            }
        }
    </script>
</body>

</html>